//
//  GQRegisterController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/5.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQRegisterController.h"
#import "GQRegisterDetailController.h"
#import "TipView.h"
#import "GQPhoneNumResult.h"
#import "GQRegisterTool.h"
#import "GQPhoneNumberParam.h"
#import <SMS_SDK/SMS_SDK.h>
#import "GQRegisterInfo.h"
#import "GQCity.h"
#import "GQProvince.h"
#import "GQRegisterAreaInfo.h"
#import "GQRegisterRegParam.h"
#import "MJExtension.h"
#import "GQRegisterRegParam.h"
#import "NSString+Hash.h"

#define kLoginTextHeight 44
#define kLoginTextMargin 10
#define kLoginViewX 0
#define kLoginViewY 20

@interface GQRegisterController () <NSXMLParserDelegate>

@property (strong, nonatomic) UITextField *phoneNumber;
@property (strong, nonatomic) UITextField *verifyNumber;
@property (strong, nonatomic) UITextField *pwdNumber;
@property (strong, nonatomic) UIView *phoneView;
@property (strong, nonatomic) UIButton *nextBtn;
@property (weak, nonatomic) NSTimer *timer;
@property (strong, nonatomic) UIButton *vertifyCodeLabel;
@property (assign, nonatomic) NSInteger count;
@property (strong, nonatomic) GQCity *city;
@property (strong, nonatomic) GQProvince *province;
@property (strong, nonatomic) NSMutableArray *cities;
@property (strong, nonatomic) NSMutableArray *provinces;

@end

@implementation GQRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBackgroundColor;
    self.view.frame = CGRectMake(0, kNavigatationBarHeight, kScreenWidth, kScreenHeight - kNavigatationBarHeight);
    self.navigationItem.title = @"注册1/2";

    [self setUpRegisterView];
    [self setUpNextBtn];
    [self setUpServerProtocol];
    [self setRegisterInfos];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"guqu_city.xml" ofType:nil];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    NSXMLParser *parse = [[NSXMLParser alloc] initWithData:data];
    parse.delegate = self;
    [parse parse];
    
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"province"]){
        self.province = [[GQProvince alloc] init];
        self.province.provinceCode = attributeDict[@"code"];
        self.province.provinceValue = attributeDict[@"value"];
        self.cities = [NSMutableArray array];
    }else if([elementName isEqualToString:@"city"]){
        self.city = [[GQCity alloc] init];
        self.city.cityCode = attributeDict[@"code"];
        self.city.cityValue = attributeDict[@"value"];

    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"province"]) {
        
        self.province.cities = self.cities;
        [self.provinces addObject:self.province];
    }else if([elementName isEqualToString:@"city"]){
        [self.cities addObject:self.city];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    [GQRegisterAreaInfo sharedGQRegisterAreaInfo].areaArr = self.provinces;
}


#pragma mark - 初始化控件

- (void)setRegisterInfos
{
    [GQRegisterInfo sharedGQRegisterInfo].icon = [UIImage imageWithRoundName:@"login_register_icon"];
    [GQRegisterInfo sharedGQRegisterInfo].name = @"未填写";
    [GQRegisterInfo sharedGQRegisterInfo].gender = @"男";
    [GQRegisterInfo sharedGQRegisterInfo].label = [NSArray arrayWithObject:@"未填写"];
    [GQRegisterInfo sharedGQRegisterInfo].location = @"未填写";
    [GQRegisterInfo sharedGQRegisterInfo].honour = @"未填写";
}

- (void)backItemDidClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setUpRegisterView
{
    CGFloat VertifyCodeBtnWidth = 90;
    CGFloat VertifyCodeBtnHeight = 30;
    
    //手机号码输入框
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(kLoginViewX, kLoginViewY + kNavigatationBarHeight, kScreenWidth, 136)];
    
    UIImageView *phoneImage =[[UIImageView alloc] initWithImage:[UIImage imageWithOriginalName:@"login_mobile"]];
    phoneImage.frame  =CGRectMake(kLoginTextMargin, 4.5, 35, 35);
    [view addSubview:phoneImage];
    
    UITextField *phoneNumber = [[UITextField alloc] initWithFrame:CGRectMake(kLoginTextMargin + phoneImage.width, 0, (kScreenWidth - kLoginTextMargin * 2) - VertifyCodeBtnWidth - phoneImage.width, kLoginTextHeight)];
    phoneNumber.backgroundColor = [UIColor whiteColor];
    phoneNumber.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneNumber.placeholder = @"手机号码";
    phoneNumber.keyboardType = UIKeyboardTypeNumberPad;
    phoneNumber.text = @"18820428175";
    self.phoneNumber = phoneNumber;
    view.backgroundColor = [UIColor whiteColor];
    
    //获取验证码
    UIButton *vertifyCodeLabel = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - kLoginTextMargin - VertifyCodeBtnWidth, phoneNumber.center.y - VertifyCodeBtnHeight / 2, VertifyCodeBtnWidth, VertifyCodeBtnHeight)];
    [vertifyCodeLabel setTitle:@"获取验证码" forState:UIControlStateNormal];
    vertifyCodeLabel.titleLabel.font = [UIFont systemFontOfSize:13];
    [vertifyCodeLabel.layer setMasksToBounds:YES];
    [vertifyCodeLabel.layer setCornerRadius:4];
    [vertifyCodeLabel.layer setBorderWidth:1];
    [vertifyCodeLabel setTitleColor:kLoginBtnColor forState:UIControlStateNormal];
    [vertifyCodeLabel addTarget:self action:@selector(getVertifyBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    self.vertifyCodeLabel = vertifyCodeLabel;
    
    
    //中间的线
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(kLoginTextMargin, 45, (kScreenWidth - kLoginTextMargin * 2), 1)];
    lineView1.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:lineView1];
    
    
    UIImageView *vertifyImage =[[UIImageView alloc] initWithImage:[UIImage imageWithOriginalName:@"login_vertify"]];
    vertifyImage.frame  =CGRectMake(kLoginTextMargin, 50.5, 35, 35);
    [view addSubview:vertifyImage];
    
    //验证码
    UITextField *verifyNumber = [[UITextField alloc] initWithFrame:CGRectMake(kLoginTextMargin + vertifyImage.width, 46, kScreenWidth - kLoginTextMargin * 2 - vertifyImage.width, kLoginTextHeight)];
    verifyNumber.backgroundColor = [UIColor whiteColor];
    verifyNumber.placeholder = @"验证码";
    verifyNumber.keyboardType = UIKeyboardTypeNumberPad;
    verifyNumber.text = @"1234";
    
    //分割线
    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(kLoginTextMargin, 91, (kScreenWidth - kLoginTextMargin * 2), 1)];
    lineView2.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:lineView2];
    
    UIImageView *lockImage =[[UIImageView alloc] initWithImage:[UIImage imageWithOriginalName:@"login_lock"]];
    lockImage.frame  =CGRectMake(kLoginTextMargin, 96.5, 35, 35);
    [view addSubview:lockImage];
    
    //设置密码
    UITextField *setPwd = [[UITextField alloc] initWithFrame:CGRectMake(kLoginTextMargin + lockImage.width, 92, kScreenWidth - kLoginTextMargin * 2 - lockImage.width, kLoginTextHeight)];
    setPwd.backgroundColor = [UIColor whiteColor];
    setPwd.placeholder = @"设置密码";
    setPwd.secureTextEntry = YES;
    setPwd.text = @"123456";
    self.pwdNumber = setPwd;
    self.verifyNumber = verifyNumber;
    [view addSubview:phoneNumber];
    [view addSubview:verifyNumber];
    [view addSubview: vertifyCodeLabel];
    [view addSubview:setPwd];
    [self.view addSubview:view];
    self.phoneView = view;
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneNumTextFieldEndEditing) name:UITextFieldTextDidEndEditingNotification object:self.phoneNumber];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pwdTextFieldDidChange) name:UITextFieldTextDidChangeNotification object:self.pwdNumber];
    
}

- (void)pwdTextFieldDidChange
{
    
    NSString *regex2 = @"^[a-zA-Z0-9]{6,15}+$";
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    BOOL isMatch2 = [pred2 evaluateWithObject:self.pwdNumber.text];
    if (isMatch2) {
        self.nextBtn.enabled = YES;
        self.nextBtn.backgroundColor = kLoginBtnColor;
    }else{
        self.nextBtn.enabled = NO;
        [self.nextBtn setBackgroundColor:[UIColor colorWithRed:138/255.0 green:148/255.0 blue:158/255.0 alpha:1.0]];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)getVertifyBtnDidClick:(UIButton *)btn
{
    //验证手机号码是否已经注册
    GQPhoneNumberParam *param = [[GQPhoneNumberParam alloc] init];
    param.account = self.phoneNumber.text;
    
    [GQRegisterTool isAccountExistWithParam:param success:^(GQPhoneNumResult *result) {
        
        //-------测试版本------
        if (![result.errorCode integerValue]) {
            NSString *regex1 = @"^1+[3578]+\\d{9}";
            NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
            BOOL isMatch1 = [pred1 evaluateWithObject:self.phoneNumber.text];
            if (!isMatch1) {
                [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"手机号码不正确"];
                return;
            }
            
            //获取验证码
            [SMS_SDK getVerificationCodeBySMSWithPhone:self.phoneNumber.text zone:@"86" result:^(SMS_SDKError *error) {
                
            }];
            
            _count = 60;
            NSTimer *myTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
            self.timer = myTimer;
            NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
            [runLoop addTimer:myTimer forMode:NSRunLoopCommonModes];
            btn.userInteractionEnabled = NO;
            [btn setBackgroundColor:[UIColor colorWithRed:18 / 255.0 green:38 / 255.0 blue:58 / 255.0 alpha:0.4]];
        }else if ([result.errorCode isEqualToString:@"2003"]){
            [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"账户已经存在"];
            return;
        }
    } failure:^(NSError *error) {
        [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"网络连接错误"];
        return;
    }];
    
    
}

- (void)setUpNextBtn
{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(kLoginTextMargin, CGRectGetMaxY(self.phoneView.frame) + kLoginViewY, (kScreenWidth - kLoginTextMargin * 2), 40)];
    [btn setBackgroundColor:[UIColor colorWithRed:18 / 255.0 green:38 / 255.0 blue:58 / 255.0 alpha:1.0]];
    [btn setTitle:@"下一步" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 5;
    btn.enabled = NO;
    [btn setBackgroundColor:[UIColor colorWithRed:138/255.0 green:148/255.0 blue:158/255.0 alpha:1.0]];
    [btn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.nextBtn = btn;
}

- (void)setUpServerProtocol
{
    
    UIFont *labelFont = [UIFont systemFontOfSize:11];
    NSString *text = @"点击下一步即代表同意古趣";
    CGFloat height = 15;
    NSDictionary *dict = @{NSFontAttributeName:labelFont};
    CGSize serviceSize = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:0 attributes:dict context:nil].size;
    UILabel *serverLabel = [[UILabel alloc] initWithFrame:CGRectMake(kLoginTextMargin, CGRectGetMaxY(self.nextBtn.frame) + kLoginTextMargin, serviceSize.width, height)];
    serverLabel.text = text;
    serverLabel.font = labelFont;
    [self.view addSubview:serverLabel];
    UIButton *serverBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(serverLabel.frame) - 2, serverLabel.center.y - height / 2 + 1, 70, 15)];
    [serverBtn setTitle:@"《服务协议》" forState:UIControlStateNormal];
    [serverBtn setTitleColor:kLoginBtnColor forState:UIControlStateNormal];
    serverBtn.titleLabel.font = labelFont;
    [self.view addSubview:serverBtn];
    
}


#pragma mark - 下一步
- (void)nextClick
{
    //验证用户名
    NSString *regex1 = @"^1+[3578]+\\d{9}";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    BOOL isMatch1 = [pred1 evaluateWithObject:self.phoneNumber.text];
    if (!isMatch1) {
        [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"手机号码不正确"];
        return;
    }
    
    [SMS_SDK commitVerifyCode:self.verifyNumber.text result:^(enum SMS_ResponseState state) {
        NSLog(@"%d", state);
        
        if (!state) {
            [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"验证码错误"];
            return;
        }else{
            NSString *regex2 = @"^[a-zA-Z0-9]{6,15}+$";
            NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
            BOOL isMatch2 = [pred2 evaluateWithObject:self.pwdNumber.text];
            
            if (!isMatch2) {
                [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"密码格式不正确"];
                return;
            }
            
            [GQRegisterRegParam sharedGQRegisterRegParam].account = [self.phoneNumber.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSString *saltStr = [self.pwdNumber.text stringByAppendingString:kSaltString];
            [GQRegisterRegParam sharedGQRegisterRegParam].pass = [saltStr hmacMD5StringWithKey:@"hexingkeji"];
            
            GQRegisterDetailController *GQRDC = [[GQRegisterDetailController alloc] init];
            GQRDC.title = @"注册2/2";
            [self.navigationController pushViewController:GQRDC animated:YES];
        }
    }];
}

- (void)countDown
{
    [self.vertifyCodeLabel setTitle:[NSString stringWithFormat:@"%ld秒后获取", _count] forState:UIControlStateNormal];
    _count--;
    if (_count == -1) {
        [self.timer invalidate];
        self.timer = nil;
        self.vertifyCodeLabel.userInteractionEnabled = YES;
        self.vertifyCodeLabel.backgroundColor = [UIColor whiteColor];
        [self.vertifyCodeLabel setTitle:@"获取验证码" forState:UIControlStateNormal];
    }
}

//懒加载

- (NSMutableArray *)provinces
{
    if (_provinces == nil) {
        _provinces = [NSMutableArray array];
    }
    return _provinces;
}

@end
